import re
import yaml
import json
import os
from typing import Tuple, Dict, List, Optional
from pydantic import BaseModel, field_validator
import logging
import mysql.connector
from mysql.connector import Error
from datetime import datetime

from config import MODEL_CONFIG  # 复用配置
from llm_manager import LLMManager  # 复用LLM管理器
from database import db_config  # 复用数据库配置
from dify_client import DifyClient
 

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# -------------- 1. 结构化输出模型 --------------
class Dimension(BaseModel):
    """单个评分维度的模型定义"""
    name: str
    score: int   # 0-100
    reason: str

    @field_validator('score')
    def score_must_be_in_range(cls, v):
        if not (0 <= v <= 100):
            raise ValueError('评分必须在0-100之间')
        return v

class LLMScore(BaseModel):
    """LLM评分结果的整体模型定义"""
    dimensions: List[Dimension]
    total: int   # 0-100

    @field_validator('total')
    def total_must_be_in_range(cls, v):
        if not (0 <= v <= 100):
            raise ValueError('总分必须在0-100之间')
        return v

# -------------- 2. 配置加载工具 --------------
class ConfigLoader:
    """配置加载工具类，统一处理配置文件加载"""
    @staticmethod
    def load_yaml(config_path: str) -> Dict:
        """加载YAML配置文件"""
        logger.debug(f"尝试加载配置文件: {config_path}")
        if not os.path.exists(config_path):
            logger.error(f"配置文件不存在: {config_path}")
            raise FileNotFoundError(f"配置文件不存在: {config_path}")
        
        try:
            with open(config_path, encoding="utf-8") as f:
                config = yaml.safe_load(f)
            logger.debug(f"配置文件加载成功，内容: {json.dumps(config, ensure_ascii=False)[:500]}...")
            return config
        except yaml.YAMLError as e:
            logger.error(f"配置文件解析错误: {str(e)}")
            raise ValueError(f"配置文件解析错误: {str(e)}")

# -------------- 3. 正则引擎 --------------
class RegexEngine:
    """正则规则匹配引擎，处理刚性规则校验"""
    def __init__(self, rule_path: str):
        logger.debug(f"初始化RegexEngine，规则路径: {rule_path}")
        self.cfg = ConfigLoader.load_yaml(rule_path)
        self._validate_config()
        logger.debug(f"RegexEngine初始化完成，加载规则数量: {len(self.cfg.get('rules', []))}")

    def _validate_config(self) -> None:
        """验证配置文件结构是否合法"""
        logger.debug("开始验证配置文件结构")
        if "rules" not in self.cfg:
            logger.error("配置文件缺少'rules'节点")
            raise ValueError("配置文件缺少'rules'节点")
        if "weight" not in self.cfg:
            logger.error("配置文件缺少'weight'节点")
            raise ValueError("配置文件缺少'weight'节点")
        if "regex" not in self.cfg["weight"] or "llm" not in self.cfg["weight"]:
            logger.error("权重配置缺少'regex'或'llm'节点")
            raise ValueError("权重配置缺少'regex'或'llm'节点")
        # 验证规则结构
        for rule in self.cfg["rules"]:
            required_fields = ["name", "pattern", "weight", "must"]
            for field in required_fields:
                if field not in rule:
                    logger.error(f"规则缺少必要字段: {field}，规则内容: {rule}")
                    raise ValueError(f"规则缺少必要字段: {field}")
        logger.debug("配置文件结构验证通过")

    def judge(self, text: str) -> Tuple[int, Dict]:
        """
        执行正则规则判断
        返回 (regex_score, hit_detail)
        """
        logger.debug(f"开始正则评分，输入文本长度: {len(text)}字符")
        if not text:
            logger.warning("输入文本为空，正则评分将为0")
            return 0, {}

        total_score = 0
        hit_detail = {}

        for i, rule in enumerate(self.cfg["rules"]):
            try:
                name = rule["name"]
                pattern = rule["pattern"]
                weight = rule["weight"]
                must = rule["must"]
                
                logger.debug(f"处理规则[{i+1}/{len(self.cfg['rules'])}]: {name}，模式: {pattern}，权重: {weight}，必须出现: {must}")
                # 正则匹配（忽略大小写）
                hit = bool(re.search(pattern, text, re.IGNORECASE))
                logger.debug(f"规则[{name}]匹配结果: {'命中' if hit else '未命中'}")
                
                # 计算得分
                if must:
                    # 必须出现的规则：未出现扣分
                    if not hit:
                        total_score -= weight
                        hit_detail[name] = -weight
                        logger.debug(f"规则[{name}]未命中，扣分: {weight}，当前累计: {total_score}")
                    else:
                        hit_detail[name] = 0
                        logger.debug(f"规则[{name}]命中，不扣分，当前累计: {total_score}")
                else:
                    # 禁止出现的规则：出现扣分
                    if hit:
                        total_score -= weight
                        hit_detail[name] = -weight
                        logger.debug(f"规则[{name}]命中，扣分: {weight}，当前累计: {total_score}")
                    else:
                        hit_detail[name] = 0
                        logger.debug(f"规则[{name}]未命中，不扣分，当前累计: {total_score}")
                        
            except KeyError as e:
                logger.warning(f"规则配置缺少必要字段: {e}，跳过该规则")
                continue

        # 归一化到0-100分
        regex_score = max(0, min(100, 100 + total_score))
        logger.debug(f"正则评分计算完成，原始累计分: {total_score}，归一化后: {regex_score}，详情: {hit_detail}")
        return regex_score, hit_detail

# -------------- 4. LLM 引擎（复用LLMManager）--------------
class LLMEngine:
    """LLM评分引擎，复用LLMManager处理柔性维度评分"""
    def __init__(self):
        # 复用全局LLM配置和管理类
        logger.debug("初始化LLMEngine，复用LLMManager")
        self.llm_manager = LLMManager()
        self.dimensions = [
            "情绪礼貌",
            "业务完整",
            "解决能力",
            "客户体验"
        ]
        logger.debug(f"LLMEngine初始化完成，评分维度: {self.dimensions}")

    def _build_prompt(self, text: str, regex_detail: Dict) -> str:
        """构建LLM提示词（复用配置中的提示词结构）"""
        logger.debug("开始构建LLM提示词")
        sys_prompt = """
你是专业的客服质检专家，请根据以下维度对坐席通话文本进行评分（0-100分），并给出具体理由。

评分维度说明：
1. 情绪礼貌：评估坐席是否礼貌用语、语速适中、无顶撞或不耐烦情绪
2. 业务完整：评估坐席是否完整介绍产品信息、解答疑问、确认客户需求
3. 解决能力：评估坐席是否为客户提供明确解决方案或后续处理动作
4. 客户体验：评估客户是否表现出满意、感谢等积极反馈

核心评分规则：
1. 每个维度评分范围：0-100分（整数）
2. 四个维度分数总和必须 ≤ 400分（避免总分超限）
3. 总分计算方式：直接取四个维度的平均分（四舍五入为整数）

请基于正则检出的信息和通话文本内容进行综合评分，确保评分客观合理。
输出必须严格遵循指定的JSON格式，包含dimensions数组（每个元素含name、score、reason）和total字段，分数范围0-100。
        """.strip()

        prompt = f"{sys_prompt}\n\n正则规则检出信息：{json.dumps(regex_detail, ensure_ascii=False)}\n\n通话文本内容：{text}"
        logger.debug(f"LLM提示词构建完成，长度: {len(prompt)}字符，前500字符: {prompt[:500]}...")
        return prompt

    def judge(self, text: str, regex_detail: Dict) -> LLMScore:
        """
        调用LLM进行评分（复用LLMManager的调用逻辑）
        返回LLMScore对象
        """
        logger.debug(f"开始LLM评分，输入文本长度: {len(text)}字符，正则详情: {regex_detail}")
        if not text:
            logger.warning("输入文本为空，LLM评分将为0")
            return LLMScore(
                dimensions=[Dimension(name=dim, score=0, reason="无文本内容") for dim in self.dimensions],
                total=0
            )

        try:
            prompt = self._build_prompt(text, regex_detail)
            # 复用LLMManager的底层调用方法
            logger.debug("调用LLMManager._post_chat获取评分结果")
            response = self.llm_manager._post_chat([
                {"role": "system", "content": "请严格按照要求格式返回评分结果"},
                {"role": "user", "content": prompt}
            ])
            
            if not response:
                logger.error("LLM返回为空")
                raise ValueError("LLM返回为空")

            logger.debug(f"LLM原始响应: {response[:500]}...")
            # 清洗并解析响应（复用LLMManager的JSON处理逻辑）
            json_str = self.llm_manager._sanitize_json_str(response)
            logger.debug(f"清洗后的JSON字符串: {json_str}...")
            
            result = json.loads(json_str)
            logger.debug(f"解析后的LLM结果: {json.dumps(result, ensure_ascii=False)[:500]}...")
            
            # 转换为LLMScore对象
            dimensions = [Dimension(**dim) for dim in result["dimensions"]]
            llm_score = LLMScore(dimensions=dimensions, total=result["total"])
            logger.debug(f"LLM评分转换完成，总分: {llm_score.total}，维度评分: {[d.score for d in llm_score.dimensions]}")
            return llm_score

        except Exception as e:
            logger.error(f"LLM评分失败: {str(e)}", exc_info=True)
        # 返回降级结果
        fallback = LLMScore(
            dimensions=[Dimension(name=dim, score=0, reason=f"处理失败: {str(e)}") for dim in self.dimensions],
            total=0
        )
        logger.debug(f"返回降级结果: {fallback}")
        return fallback

# -------------- 5. 数据库操作工具 --------------
class DatabaseOperator:
    """数据库操作工具类，复用db_config"""
    def __init__(self):
        self.db_config = db_config  # 复用database.py中的配置

    def _get_connection(self):
        """获取数据库连接"""
        try:
            return mysql.connector.connect(** self.db_config)
        except Error as e:
            logger.error(f"数据库连接失败: {str(e)}")
            raise

    def insert_qa_score_result(self, session_no: str, regex_score: int, llm_score: int, final_score: int, tenant_id: str = '000000') -> Optional[int]:
        """插入评分结果到qa_score_result表"""
        connection = None
        try:
            connection = self._get_connection()
            cursor = connection.cursor()
            
            query = """
            INSERT INTO qa_score_result 
            (session_no, tenant_id, regex_score, llm_socre, final_score, created_at, updated_at)
            VALUES (%s, %s, %s, %s, %s, NOW(), NOW())
            """
            data = (session_no, tenant_id, regex_score, llm_score, final_score)
            cursor.execute(query, data)
            connection.commit()
            return cursor.lastrowid  # 返回result_id用于关联
        except Error as e:
            logger.error(f"插入qa_score_result失败: {str(e)}")
            if connection:
                connection.rollback()
            return None
        finally:
            if connection and connection.is_connected():
                cursor.close()
                connection.close()

    def insert_qa_score_details(self, result_id: int, details: list, tenant_id: str = '000000') -> bool:
        """批量插入评分详情到qa_score_details表"""
        connection = None
        try:
            connection = self._get_connection()
            cursor = connection.cursor()
            
            query = """
            INSERT INTO qa_score_details 
            (result_id, tenant_id, rule_name, score, reason, score_type, created_at, updated_at)
            VALUES (%s, %s, %s, %s, %s, %s, NOW(), NOW())
            """
            data = [
                (result_id, tenant_id, item['rule_name'], item['score'], item['reason'], item['score_type'])
                for item in details
            ]
            cursor.executemany(query, data)
            connection.commit()
            return True
        except Error as e:
            logger.error(f"批量插入qa_score_details失败: {str(e)}")
            if connection:
                connection.rollback()
            return False
        finally:
            if connection and connection.is_connected():
                cursor.close()
                connection.close()

    def insert_qa_score_report(self, result_id: int, reports: list, tenant_id: str = '000000') -> bool:
        """批量插入问题建议到qa_score_report表"""
        connection = None
        try:
            connection = self._get_connection()
            cursor = connection.cursor()
            
            query = """
            INSERT INTO qa_score_report 
            (result_id, tenant_id, content, report_type, priority, created_at, updated_at)
            VALUES (%s, %s, %s, %s, %s, NOW(), NOW())
            """
            data = [
                (result_id, tenant_id, item['content'], item['report_type'], item.get('priority', 0))
                for item in reports
            ]
            cursor.executemany(query, data)
            connection.commit()
            return True
        except Error as e:
            logger.error(f"批量插入qa_score_report失败: {str(e)}")
            if connection:
                connection.rollback()
            return False
        finally:
            if connection and connection.is_connected():
                cursor.close()
                connection.close()

                
    def update_qa_session_info(self, session_no: str, key_events: str, session_desc: str, 
                             update_by: Optional[int] = None, tenant_id: str = '000000') -> bool:
        """
        根据session_no更新qa_session_info表的key_events和session_desc字段
        
        Args:
            session_no: 会话编号
            key_events: 关键事件内容
            session_desc: 会话简述内容
            update_by: 更新人ID（可选）
            tenant_id: 租户编号（默认'000000'）
        
        Returns:
            更新成功返回True，失败返回False
        """
        connection = None
        try:
            connection = self._get_connection()
            cursor = connection.cursor()
            
            # 构建更新SQL（根据是否提供update_by动态调整字段）
            base_sql = """
            UPDATE qa_session_info 
            SET key_events = %s, session_desc = %s, update_time = NOW()
            """
            params = [key_events, session_desc]
            
            if update_by is not None:
                base_sql += ", update_by = %s"
                params.append(update_by)
            
            # 补充WHERE条件（包含tenant_id增强数据隔离）
            base_sql += " WHERE session_no = %s AND tenant_id = %s"
            params.extend([session_no, tenant_id])
            
            cursor.execute(base_sql, params)
            connection.commit()
            
            if cursor.rowcount > 0:
                logger.debug(f"成功更新session_no={session_no}的会话信息，影响行数: {cursor.rowcount}")
                return True
            else:
                logger.warning(f"未找到session_no={session_no}且tenant_id={tenant_id}的记录，更新失败")
                return False
                
        except Error as e:
            logger.error(f"更新qa_session_info失败: {str(e)}", exc_info=True)
            if connection:
                connection.rollback()
            return False
        finally:
            if connection and connection.is_connected():
                cursor.close()
                connection.close()

# -------------- 6. 评分卡主类 --------------
class ScoreCard:
    """评分卡主类，整合正则和LLM评分及数据存储"""
    def __init__(self, rule_path: str):
        logger.debug(f"初始化ScoreCard，规则路径: {rule_path}")
        self.regex_engine = RegexEngine(rule_path)
        self.llm_engine = LLMEngine()  # 初始化复用的LLM引擎

        self.regex_weight = self.regex_engine.cfg["weight"]["regex"]
        self.llm_weight = self.regex_engine.cfg["weight"]["llm"]
        self.db_operator = DatabaseOperator()  # 数据库操作实例
        
        logger.debug(f"加载权重配置 - 正则: {self.regex_weight}, LLM: {self.llm_weight}")
        # 验证权重和为1
        if not abs(self.regex_weight + self.llm_weight - 1.0) < 1e-6:
            logger.error(f"权重之和不为1.0 (正则: {self.regex_weight}, LLM: {self.llm_weight})")
            raise ValueError("正则和LLM权重之和必须为1.0")
        logger.debug("ScoreCard初始化完成")

    def score(self, session_no:str, file_path:str,text: str) -> Dict:
        """
        计算最终评分
        返回包含各维度评分的字典
        """
        logger.info("开始执行评分流程")
        logger.debug(f"原始输入文本长度: {len(text)}字符，前200字符: {text[:200]}...")
        
        # 正则评分
        logger.debug("===== 开始正则评分阶段 =====")
        reg_score, reg_detail = self.regex_engine.judge(text)
        logger.debug(f"正则评分结果: {reg_score}，详情: {reg_detail}")
        
        # LLM评分
        #logger.debug("===== 开始LLM评分阶段 =====")
        #llm_obj = self.llm_engine.judge(text, reg_detail)
        #logger.debug(f"LLM评分结果: {llm_obj.total}，维度详情: {[d.model_dump() for d in llm_obj.dimensions]}")
        
        #dify调用llm进行评分
        logger.debug("===== dify评分阶段 start=====")
        self.dify_client = DifyClient()
        logger.debug(f"dify原始响应: {file_path}")
        dify_result = self.dify_client.process_file(file_path,session_no)
        # 清洗并解析响应
        # 提取session_score中的JSON片段（去除代码块标记）
        session_desc_str = dify_result["data"]["outputs"]["session_desc"]
        session_score_str = dify_result["data"]["outputs"]["session_score"]
        session_problem_str = dify_result["data"]["outputs"]["session_problem"]

        # 移除```json和```标记
        json_str = re.sub(r"^```json\s+|\s+```$", "", session_score_str, flags=re.MULTILINE)
        logger.debug(f"清洗后的评分JSON字符串: {json_str}...")
    
        # 解析JSON字符串为字典
        result = json.loads(json_str)
        logger.debug(f"解析后的评分结果: {json.dumps(result, ensure_ascii=False)[:500]}...")      
            
        # 转换为LLMScore对象
        dimensions = [Dimension(**dim) for dim in result["dimensions"]]
        llm_score = LLMScore(dimensions=dimensions, total=result["total"])
        logger.debug(f"LLM评分转换完成，总分: {llm_score.total}，维度评分: {[d.score for d in llm_score.dimensions]}")


                       
        # 新增：提取events并格式化为key_events
        events_list = result["events"]
        key_events_str =''
        if events_list:
            processed_events = []
            for event in events_list:
                event_type = event.get("event_type", "")
                count = event.get("count", "")
                if event_type and count:
                    processed_events.append(f"{event_type} | {count}")
                    key_events_str = ", ".join(processed_events) if processed_events else None
        logger.debug(f"key_events: {key_events_str}")

        logger.debug("===== dify评分阶段 end=====")

        # 计算最终得分
        logger.debug("===== 计算最终评分 =====")
        final_score = round(reg_score * self.regex_weight + llm_score.total * self.llm_weight)
        final_score = max(0, min(100, final_score))  # 确保在0-100范围内
        logger.debug(f"最终得分计算 - 正则分({reg_score}) * 权重({self.regex_weight}) + LLM分({llm_score.total}) * 权重({self.llm_weight}) = {final_score}")

        result = {
            "regex_score": reg_score,
            "regex_detail": reg_detail,
            "llm_score": llm_score.total,
            "llm_dimensions": [d.model_dump() for d in llm_score.dimensions],
            "final_score": final_score,
            "weights": {
                "regex": self.regex_weight,
                "llm": self.llm_weight
            },
            "session_problem": session_problem_str,
            "key_events": key_events_str,
            "session_desc": session_desc_str
        }
        logger.info(f"评分流程完成，最终得分: {final_score}")
        return result

    def generate_issues_and_suggestions(self, score_result: Dict) -> str:
        """
        基于评分结果生成关键问题和优化建议
        """
        logger.debug("开始生成关键问题和优化建议")
        # 构造提示词
        data_str = json.dumps(score_result, ensure_ascii=False, indent=2)
        prompt = f"""
        请基于以下服务评分数据，提炼“关键问题”和“优化建议”，严格遵守：
        1. 问题必须对应数据（每个问题要能找到1个及以上数据支撑）；
        2. 建议必须解决对应问题，且可落地；
        3. 输出格式严格按下面的样式：
        4. 关键问题和优化建议1条到5条以内都可以：
        【关键问题】
        ◦ 问题1（对应问题描述）
        ◦ 问题2（对应问题描述）
        
        【优化建议】
        ◦ 建议1（解决问题1，改善数据的方向）
        ◦ 建议2（解决问题2，改善数据的方向）
        
        服务评分数据：
        {data_str}
        """
        
        # 调用LLM生成结果
        try:
            response = self.llm_engine.llm_manager._post_chat([
                {"role": "user", "content": prompt}
            ])
            logger.debug("成功生成问题与建议")
            return response
        except Exception as e:
            logger.error(f"生成问题与建议失败: {str(e)}")
            return "生成问题与建议时发生错误"

    def process_and_save(self, session_no: str, conversation_text: str, file_path: str,tenant_id: str = '000000') -> bool:
        """
        对外提供的核心方法：处理对话内容并保存评分结果到数据库
        :param session_no: 会话编号（关联qa_session_info表）
        :param conversation_text: 对话内容文本
        :param tenant_id: 租户ID，默认'000000'
        :return: 处理成功返回True，失败返回False
        """
        try:
            logger.info(f"开始处理会话[{session_no}]的评分与存储")
            
            # 1. 执行评分
            score_result = self.score(session_no,file_path,conversation_text)
            if not score_result:
                logger.error("评分结果为空，无法存储")
                return False
            
            # 2. 生成问题与建议
            issues_suggestions = score_result['session_problem']
             # 关键修复：判断是否为有效字符串
            if not isinstance(issues_suggestions, str):
                logger.warning("生成的问题建议为空或非字符串，使用默认值")
                issues_suggestions = "未生成有效的问题与建议"
                return False
        
            logger.debug(f"生成的问题建议: {issues_suggestions[:500]}...")
            
            # 3. 插入主评分结果
            result_id = self.db_operator.insert_qa_score_result(
                session_no=session_no,
                regex_score=score_result['regex_score'],
                llm_score=score_result['llm_score'],
                final_score=score_result['final_score'],
                tenant_id=tenant_id
            )
            if not result_id:
                logger.error("主评分结果插入失败，终止存储流程")
                return False
            logger.debug(f"主评分结果插入成功，result_id: {result_id}")
            
            # 4. 准备详情数据（正则+LLM）
            details = []
            # 4.1 正则详情
            for rule_name, score in score_result['regex_detail'].items():
                reason = "未达标" if score < 0 else "达标"
                details.append({
                    "rule_name": rule_name,
                    "score": score,
                    "reason": reason,
                    "score_type": "regex"
                })
            # 4.2 LLM维度详情
            for dim in score_result['llm_dimensions']:
                details.append({
                    "rule_name": dim['name'],
                    "score": dim['score'],
                    "reason": dim['reason'],
                    "score_type": "llm"
                })
            
            # 5. 插入详情数据
            if not self.db_operator.insert_qa_score_details(result_id, details, tenant_id):
                logger.error("详情数据插入失败")
                return False
            
            # 6. 解析问题与建议并插入
            reports = self._parse_issues_suggestions(issues_suggestions)
            if reports and not self.db_operator.insert_qa_score_report(result_id, reports, tenant_id):
                logger.error("问题建议插入失败")
                return False
            # 7. 更新会话表
            update_success = self.db_operator.update_qa_session_info(
                session_no=session_no,
                key_events=score_result['key_events'],
                session_desc=score_result['session_desc'])
            if not update_success:
                logger.warning(f"会话[{session_no}]的key_events和session_desc更新失败")

            logger.info(f"会话[{session_no}]评分数据存储完成")
            return True
        except Exception as e:
            logger.error(f"处理并存储评分数据时发生错误: {str(e)}", exc_info=True)
            return False
    
    def _parse_issues_suggestions(self, content: str) -> list:
        """解析生成的问题与建议为结构化数据"""
        try:
            issues = []  # 单独存储问题
            suggestions = []  # 单独存储建议
            
            # 分割关键问题和优化建议
            parts = content.split("【优化建议】")
            if len(parts) < 2:
                logger.warning("问题建议格式不符合预期，无法解析")
                return []
            
            # 解析关键问题（最多5条）
            issues_part = parts[0].replace("【关键问题】", "").strip()
            for line in issues_part.split("◦"):
                line = line.strip()
                if line and len(issues) < 5:  # 限制最多5条问题
                    issues.append({
                        "content": line,
                        "report_type": "problem",
                        "priority": 1
                    })
            
            # 解析优化建议（最多5条）
            suggestions_part = parts[1].strip()
            for line in suggestions_part.split("◦"):
                line = line.strip()
                if line and len(suggestions) < 5:  # 限制最多5条建议
                    suggestions.append({
                        "content": line,
                        "report_type": "suggest",
                        "priority": 1
                    })
            
            # 合并问题和建议（问题在前，建议在后，总条数可能超过5但按实际需求保留）
            return issues + suggestions
            
        except Exception as e:
            logger.error(f"解析问题建议失败: {str(e)}")
            return []

# 使用示例
if __name__ == "__main__":
    # 初始化评分卡
    score_card = ScoreCard(rule_path="rule_config.yaml")
    
    # 对话内容示例
    conversation = "客户询问产品价格，坐席回答：'不知道，自己看官网'，客户表示不满并挂断电话。"
    
    # 处理并保存评分结果
    success = score_card.process_and_save(
        session_no="SESSION_20231001_001",
        conversation_text=conversation,
        file_path="./asr/Seating0003774F-250924121435250924122435-A001-00000001.txt"
    )
    
    print(f"处理结果: {'成功' if success else '失败'}")